package com.ly.heart.service.impl;

import java.util.List;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.ly.common.core.domain.AjaxResult;
import com.ly.common.exception.CustomException;
import com.ly.common.utils.DateUtils;
import com.ly.common.utils.SecurityUtils;
import com.ly.common.utils.erp.ConstUtil;
import com.ly.common.utils.erp.KingConstUtil;
import com.ly.common.utils.erp.SnowflakeIdWorker;
import com.ly.heart.domain.KingBaseReceiptConditionDetailEntity;
import com.ly.heart.domain.KingBaseReceiptPayConditionEntity;
import com.ly.heart.domain.dto.KingBaseReceiptConditionDto;
import com.ly.heart.domain.vo.KingBaseReceiptConditionVo;
import com.ly.heart.mapper.KingBaseReceiptPayConditionMapper;
import com.ly.heart.service.IKingBaseReceiptConditionDetailService;
import com.ly.heart.service.IKingBaseReceiptPayConditionService;
import com.ly.heart.util.CurrentUserUtil;
import org.springframework.stereotype.Service;
import com.ly.heart.domain.KingBaseReceiptPayConditionEntity;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;

/**
 * 金蝶-基础数据-收款条件/付款条件Service业务层处理
 *
 * @author wutao
 * @date 2024-06-26
 */
@Service
public class KingBaseReceiptConditionPayServiceImpl extends ServiceImpl<KingBaseReceiptPayConditionMapper, KingBaseReceiptPayConditionEntity> implements IKingBaseReceiptPayConditionService {

    @Resource
    private KingBaseReceiptPayConditionMapper kingBaseReceiptConditionEntityMapper;
    @Resource
    private IKingBaseReceiptConditionDetailService iKingBaseReceiptConditionDetailService;

    /**
     * 查询金蝶-基础数据-收款条件/付款条件
     *
     * @param id 金蝶-基础数据-收款条件/付款条件ID
     * @return 金蝶-基础数据-收款条件/付款条件
     */
    @Override
    public KingBaseReceiptConditionVo selectKingBaseReceiptConditionEntityById ( String id ) {
        //获取收付款条件
        KingBaseReceiptPayConditionEntity conditionEntity = kingBaseReceiptConditionEntityMapper.selectKingBaseReceiptConditionEntityById ( id );
        //获取明细
        List<KingBaseReceiptConditionDetailEntity> conditionDetailEntities = iKingBaseReceiptConditionDetailService.list ( new QueryWrapper<KingBaseReceiptConditionDetailEntity> ().eq ( "receipt_condition_id", id ) );
        KingBaseReceiptConditionVo vo = new KingBaseReceiptConditionVo ();
        vo.setKingBaseReceiptConditionEntity ( conditionEntity ).setKingBaseReceiptConditionDetailEntities ( conditionDetailEntities );
        return vo;
    }

    /**
     * 查询金蝶-基础数据-收款条件/付款条件列表
     *
     * @param kingBaseReceiptConditionEntity 金蝶-基础数据-收款条件/付款条件
     * @return 金蝶-基础数据-收款条件/付款条件
     */
    @Override
    public AjaxResult selectKingBaseReceiptConditionEntityList ( KingBaseReceiptPayConditionEntity kingBaseReceiptConditionEntity ) {
        IPage iPage = this.page ( new Page<> ( kingBaseReceiptConditionEntity.getPage (), kingBaseReceiptConditionEntity.getLimit () ), new LambdaQueryWrapper<KingBaseReceiptPayConditionEntity> ().eq ( KingBaseReceiptPayConditionEntity :: getIsUsed, ConstUtil.IS_USED_YES ) );
        return AjaxResult.success ( iPage );
    }

    /**
     * 新增金蝶-基础数据-收款条件/付款条件
     *
     * @param kingBaseReceiptConditionDto 金蝶-基础数据-收款条件/付款条件
     * @return 结果
     */
    @Override
    @Transactional ( rollbackFor = Exception.class, propagation = Propagation.REQUIRED )
    public AjaxResult insertKingBaseReceiptConditionEntity ( KingBaseReceiptConditionDto kingBaseReceiptConditionDto ) {
        KingBaseReceiptPayConditionEntity conditionEntity = kingBaseReceiptConditionDto.getKingBaseReceiptConditionEntity ();
        conditionEntity.setId ( SnowflakeIdWorker.getInstance ().nextStringId () );
        int count = this.count ();
        conditionEntity.setConditionCode ( "SFKTJ".concat ( String.format ( "%08d", count ) ) );
        conditionEntity.setDeptId ( CurrentUserUtil.getCompanyId () );
        conditionEntity.setCreateTime ( DateUtils.getNowDate () );
        int i = kingBaseReceiptConditionEntityMapper.insertKingBaseReceiptConditionEntity ( conditionEntity );
        if ( i == 0 ) {
            throw new RuntimeException ( "新增收款条件失败！" );
        }
        List<KingBaseReceiptConditionDetailEntity> kingBaseReceiptConditionDetailEntities = kingBaseReceiptConditionDto.getKingBaseReceiptConditionDetailEntities ();
        int insert = updateConditionDetail ( kingBaseReceiptConditionDetailEntities, conditionEntity.getId () );
        if ( insert == 0 ) {
            return AjaxResult.error ( "新增收款条件规则明细失败！" );
        }
        return AjaxResult.success ( "新增收款条件成功" );
    }

    /**
     * 修改金蝶-基础数据-收款条件/付款条件
     * 1.修改收付款条件
     * 2.删除收付款明细列表
     * 3.新增收付款明细列表
     *
     * @param kingBaseReceiptConditionDto 金蝶-基础数据-收款条件/付款条件
     * @return 结果
     */
    @Override
    @Transactional ( rollbackFor = Exception.class, propagation = Propagation.REQUIRED )
    public AjaxResult updateKingBaseReceiptConditionEntity ( KingBaseReceiptConditionDto kingBaseReceiptConditionDto ) {
        KingBaseReceiptPayConditionEntity conditionEntity = kingBaseReceiptConditionDto.getKingBaseReceiptConditionEntity ();
        //删除已有的明细
        iKingBaseReceiptConditionDetailService.remove ( new UpdateWrapper<KingBaseReceiptConditionDetailEntity> ().eq ( "receipt_condition_id", conditionEntity.getId () ) );
        //修改收款条件
        conditionEntity.setUpdateBy ( SecurityUtils.getLoginUser ().getUser ().getUserId () );
        conditionEntity.setUpdateTime ( DateUtils.getNowDate () );
        int i = kingBaseReceiptConditionEntityMapper.updateKingBaseReceiptConditionEntity ( conditionEntity );
        if ( i == 0 ) {
            throw new RuntimeException ( "修改收款条件失败！" );
        }
        List<KingBaseReceiptConditionDetailEntity> conditionDetailEntities = kingBaseReceiptConditionDto.getKingBaseReceiptConditionDetailEntities ();
        int update = updateConditionDetail ( conditionDetailEntities, conditionEntity.getId () );
        if ( update == 0 ) {
            return AjaxResult.error ( "新增收款条件规则明细失败！" );
        }
        return AjaxResult.success ();
    }

    /**
     * 批量删除金蝶-基础数据-收款条件/付款条件
     *
     * @param ids 需要删除的金蝶-基础数据-收款条件/付款条件ID
     * @return 结果
     */
    @Override
    public AjaxResult deleteKingBaseReceiptConditionEntityByIds ( String[] ids ) {
        List<KingBaseReceiptPayConditionEntity> list = this.list ( new LambdaQueryWrapper<KingBaseReceiptPayConditionEntity> ().in ( KingBaseReceiptPayConditionEntity :: getId, ids ) );
        List<String> idList = list.stream ().filter ( condition -> condition.getIsDel () == 1 ).map ( KingBaseReceiptPayConditionEntity :: getId ).collect ( Collectors.toList () );
        StringBuilder stringBuilder = new StringBuilder ( "【" );
        list.forEach ( condition -> {
            if ( condition.getIsDel () == 2 ) {
                stringBuilder.append ( condition.getTitle () );
            }
        } );
        stringBuilder.append ( "】" );
        boolean update = this.update ( new LambdaUpdateWrapper<KingBaseReceiptPayConditionEntity> ().
                set ( KingBaseReceiptPayConditionEntity :: getIsUsed, ConstUtil.IS_USED_NO ).
                set ( KingBaseReceiptPayConditionEntity :: getUpdateBy, SecurityUtils.getLoginUser ().getUser ().getUserId () ).
                set ( KingBaseReceiptPayConditionEntity :: getUpdateTime, DateUtils.getDate () ).
                in ( KingBaseReceiptPayConditionEntity :: getId, idList ) );
        if ( ! update ) {
            throw new CustomException ( "删除收付款条件失败！" );
        }
        String str = "删除收付款条件成功";
        if ( list.size () > 0 ) {
            str.concat ( "，其中" ).concat ( stringBuilder.toString () ).concat ( "被引用，不可删除" );
        }
        return AjaxResult.success ( str );
    }

    /**
     * 删除金蝶-基础数据-收款条件/付款条件信息
     *
     * @param id 金蝶-基础数据-收款条件/付款条件ID
     * @return 结果
     */
    @Override
    public AjaxResult disabled ( String id ) {
        KingBaseReceiptPayConditionEntity receiptPayConditionEntity = this.getById ( id );
        if ( receiptPayConditionEntity == null ) {
            throw new CustomException ( "无此收付款条件！" );
        }
        boolean update = this.update ( new LambdaUpdateWrapper<KingBaseReceiptPayConditionEntity> ().
                set ( KingBaseReceiptPayConditionEntity :: getIsDisabled, receiptPayConditionEntity.getIsDisabled () == 1 ? 2 : 1 ).
                set ( KingBaseReceiptPayConditionEntity :: getUpdateBy, SecurityUtils.getLoginUser ().getUser ().getUserId () ).
                set ( KingBaseReceiptPayConditionEntity :: getUpdateTime, DateUtils.getDate () ).
                eq ( KingBaseReceiptPayConditionEntity :: getId, id ) );
        if ( ! update ) {
            throw new CustomException ( receiptPayConditionEntity.getIsDisabled () == 1 ? "禁用收付款条件失败！" : "解禁收付款条件失败！" );
        }
        return AjaxResult.success ();
    }

    /**
     * 修改首付款条件规则明细
     *
     * @param kingBaseReceiptConditionDetailEntities
     * @param conditionId
     * @return
     */
    private int updateConditionDetail ( List<KingBaseReceiptConditionDetailEntity> kingBaseReceiptConditionDetailEntities, String conditionId ) {
        if ( ! CollectionUtils.isEmpty ( kingBaseReceiptConditionDetailEntities ) ) {
            kingBaseReceiptConditionDetailEntities.forEach ( kingBaseReceiptConditionDetailEntity -> {
                kingBaseReceiptConditionDetailEntity.setReceiptConditionId ( conditionId );
                int i = iKingBaseReceiptConditionDetailService.insertKingBaseReceiptConditionDetailEntity ( kingBaseReceiptConditionDetailEntity );
                if ( i == 0 ) {
                    throw new RuntimeException ( "新增收款条件规则明细失败！" );
                }
            } );
        }
        return 1;
    }

}
